<template>
  <div class='container'>
    <el-dialog
      :title="dialogForm.id ? '修改标签' : '新增标签'"
      :visible="dialogVisible"
      width="400px"
      @close='close'>
      <el-form :model="dialogForm" ref="dialogForm" :rules="dialogFormRules">
        <el-form-item label="所属学科" prop="subjectID" label-width="80px" v-if="!id">
          <el-select v-model="dialogForm.subjectID" placeholder="请选择" @focus="focus" style="width: 280px">
            <el-option
              v-for="item in simpleList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" label-width="80px" prop="tagName">
          <el-input v-model="dialogForm.tagName" placeholder="请输入学科名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/tags'
export default {
  name: 'TagsAdd',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    }
  },
  watch: {
    id: {
      deep: true,
      handler (val) {
        if (!this.id) {
          this.dialogForm.subjectID = ''
        } else {
          this.dialogForm.subjectID = +this.id
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      dialogFormRules: {
        tagName: [
          { required: true, message: '请输入标签名称' }
        ]
      },
      dialogForm: {
        tagName: '',
        subjectID: ''
      },
      simpleList: []
    }
  },
  methods: {
    close () {
      this.$emit('update:dialogVisible', false)
      this.$refs.dialogForm.resetFields()
      this.dialogForm = {
        tagName: '',
        subjectID: ''
      }
    },
    async add () {
      try {
        await this.$refs.dialogForm.validate()
      } catch {
        return false
      }
      if (this.dialogForm.id) {
        await update(this.dialogForm)
        this.$message.success('修改标签成功')
      } else {
        await add(this.dialogForm)
        this.$emit('page', 1)
        this.$message.success('新增标签成功')
      }
      this.$emit('getTagsList')
      this.close()
    },
    async focus () {
      const { data } = await simple()
      this.simpleList = data
    }
  }
}
</script>

<style scoped lang='scss'></style>
